package cn.ckx.coding.common.utils.date;

import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 
 *  输入毫秒数，输出带时间单位的对应中文时间描述
 * 不支持非整数表示，时间单位转换后不是整数时，显示为对应毫秒数
 * 
 */
public class TimeDescriptionUtils {

    static Map<Long, Function<Long, String>> container = new TreeMap<Long, Function<Long, String>>().descendingMap();

    private static final long S = 1000L;

    static {
        bind(0L, ms -> String.format("%d毫秒", ms));
        bind(S, ms -> String.format("%d秒", TimeUnit.MILLISECONDS.toSeconds(ms)));
        bind(60 * S, ms -> String.format("%d分钟", TimeUnit.MILLISECONDS.toMinutes(ms)));
        bind(60 * 60 * S, ms -> String.format("%d小时", TimeUnit.MILLISECONDS.toHours(ms)));
        bind(24* 60 * 60 * S, ms -> String.format("%d天", TimeUnit.MILLISECONDS.toDays(ms)));
    }

    public static void bind(Long minutes, Function<Long, String> content) {
        container.put(minutes, content);
    }

    public static String get(Long minutes) {
        return container.entrySet()
                .stream()
                .filter(x -> minutes >= x.getKey())
                .filter(x -> x.getKey() == 0 || minutes % x.getKey() == 0)
                .findFirst()
                .map(Map.Entry::getValue)
                .orElse(m -> "")
                .apply(minutes);
    }

}
